<!--接触职业病危害因素人员管理情况普查表-->
<template>
  <Layout>
    <Form ref="queryForm" :model="dataToQuery" :label-width="120">
      <Row class="query-form">
        <Col span="8">
          <FormItem label='填报单位：'>
            <cascaderDom class="query-form-el" ref="queryOrgCascader" style="width: 100%;"
                         @setOrgInfo='setOrgId'
                         @setOrgname='setOrgName'
                         :orgTree="true"></cascaderDom>
          </FormItem>
        </Col>
        <Col span="8">

        </Col>


        <Col span="8" v-if="!switchFlag">
          <!--          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
        <Col span="8" v-else>
          <FormItem label='隐患分类：'>
            <Cascader :data="areaTree" v-model="dataToQuery.dangerSortArr" change-on-select :transfer="true"
                      @on-change="(value,selectedData)=>{$set(dataToQuery,'dangerSort',value.join(','))}"></Cascader>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label='整改责任人：' prop='persionHeld'>
            <Input class='' placeholder="请填写整改责任人" type='text' v-model='dataToQuery.persionHeld'></Input>
          </FormItem>
        </Col>


      </Row>
      <Row v-show="switchFlag" class="query-form">

        <Col span="8" :offset="16">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>

        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
           :loading='pageStatus.loading ||  pageStatus.baseLoading'
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>
    <Modal :mask-closable="false" :title="mode == 'view' ?'职业安全管理现状普查表详情':'职业安全管理现状普查表'" :transfer=false
           v-model="dialogShow" v-if="dataToView && dialogShow"
           :width=1200 :styles="{height:'620px'}" class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="dataToView" :class="mode === 'view'?'modal-view-detail':'modal-form'" :show-message="false"
                :model="dataToView.healthCompany" :rules="mode === 'view'?{} :ruleCustom"
                :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?160:null">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='填报单位：' prop='companyId'>
                  <div v-if="mode === 'view'">{{ dataToView.healthCompany.companyName }}</div>
                  <cascaderDom v-else class="query-form-el" ref="groupOrg"
                               @setOrgInfo='(data)=>{cascaderDomIdChangeHandle(data,"companyId");}'
                               @setOrgname='(data)=>{cascaderDomNameChangeHandle(data,"companyName");}'
                               :currentOrgId="dataToView.healthCompany.companyId"
                               :setCurrentName="{label:dataToView.healthCompany.companyName, value:dataToView.healthCompany.companyId}"
                               :orgTree="true"></cascaderDom>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='所属二级集团：'>
                  <div v-if="mode === 'view'">{{ dataToView.healthCompany.twoLevelOrgName }}</div>
                  <Input v-else class='' placeholder="请填写所属二级集团" type='text' readonly
                         v-model='dataToView.healthCompany.twoLevelOrgName'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='填报日期：' prop='createDate'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.healthCompany.createDate) }}</div>
                  <Input v-else class="w" readonly  placeholder="请选择填报日期" v-model='dataToView.healthCompany.createDate'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='填报人：' prop='createUserName'>
                  <div v-if="mode === 'view'">{{ dataToView.healthCompany.createUserName }}</div>
                  <Input v-else class='' readonly placeholder="请填写填报人" type='text' v-model='dataToView.healthCompany.createUserName'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='联系方式：' prop='phone'>
                  <div v-if="mode === 'view'">{{ dataToView.healthCompany.phone }}</div>
                  <Input v-else class='' placeholder="请填写联系方式" type='text' v-model='dataToView.healthCompany.phone'></Input>
                </FormItem>
              </Col>
              <Col span="11">

              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg" v-if="mode != 'view'">
              <Col span="23">
                <Button icon="md-add" class="ivu-btn-add" @click="addItemInfo">选择模版</Button>
              </Col>
            </Row>
            <Row v-if="mode === 'view'" type="flex" justify="space-around" class="code-row-bg">
              <Col span="23" >
                <Table  ref='tableItem' :height="350" no-data-text="没有查询到相关数据!"
                        border :columns="columnsView" :data="dataItem">
                </Table>
              </Col>
            </Row>
            <Row v-else type="flex" justify="space-around" class="code-row-bg">
              <Col span="23" >
                <Table  ref='tableItem' :height="250" no-data-text="没有查询到相关数据!"
                        border :columns="columnsItem" :data="dataItem">
                  <template slot-scope="{ row, index }" slot="whether">
                    <Select v-model="dataItem[index].whether" style="width:100%"  transfer="true">
                      <Option  value="1" >是</Option>
                      <Option  value="0" >否</Option>
                    </Select>
                  </template>
                </Table>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dataToView')">确定</Button>
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>

    <Modal title="职业安全管理现状普查表模版" :transfer=false  v-model="templateMod" :width=900>
      <safetyTemplate v-if="templateMod" ref="safetyTemplate" ></safetyTemplate>
      <div slot="footer">
        <Button type="primary" class='ivu-btn-save' @click="saveItem">确定</Button>
        <Button  type="primary" class='ivu-btn-cancel' @click="templateModCancel">取消</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import {formatDate} from '@/tools/index'
import pageCommonFunction from '@/components/pageCommonFunction.js'
import safetyTemplate from '@/views/safe/health/safety/template.vue'

var cascaderDom = () => import('@/components/cascader-dom.vue');
export default {
  components: {
    cascaderDom,safetyTemplate
  },
  data() {
    return {
      ...this.createCommonDataField(),
      templateMod:false,
      switchFlag: false,
      uploadFile: null,
      buttonLoading1: false,
      importModal: false,
      dataItem: [],
      token: sessionStorage('token').get('Authorization'),
      user: sessionStorage('userId').getObject('userId'),
      columns1: [
        {title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {key: 'companyName', title: '填报单位', align: 'center', minWidth: 170, tooltip: true,render:this.getColumKey},
        {key: 'createDate', title: '填报日期', align: 'center', minWidth: 120,render:this.renderCellDateAsHealth },
        {key: 'createUserName', title: '填报人', align: 'center', minWidth: 120,render:this.getColumKey},
        {key: 'phone', title: '联系方式', align: 'center', minWidth: 120,render:this.getColumKey},
        {key: 'twoLevelOrgName', title: '所属二级集团', align: 'center', minWidth: 170, tooltip: true,render:this.getColumKey},
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 200,
          align: 'center',
          render: (h, params) => {
            if (this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.healthCompany.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                    ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.download(params);
                    }
                  }
                }, '导出'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.viewData(params);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  disabled: true,
                  style: {fontSize: '14px'},
                  on: {
                    click: () => {
                      this.editData(params);
                    }
                  }
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: 'red'},
                  on: {
                    click: () => {
                      this.deleteData(params);
                    }
                  }
                }, '删除')
              ]);
            } else {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.download(params);
                    }
                  }
                }, '导出'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.viewData(params);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            }
          }
        }
      ],
      columnsItem: [
        {title: '序号', width: 80, fixed: 'left', align: 'center', key: 'index',render:(h,params)=>{return h('span', params.index+1)}},
        { key:'evaluateItem', title: '评价项目' ,  align: 'center',minWidth: 120 },
        { key:'evaluationContent',title: '评价内容',  align: 'center',minWidth: 170,tooltip: true },
        { slot:'whether',title: '是/否',  align: 'center',minWidth: 80 },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 120,
          align: 'center',
          render: (h, params) => {

            return h('div', [
              h('A', {
                props: {type: 'primary', size: 'small'},
                style: {fontSize: '14px', color: 'red'},
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '提示',
                      content: '<p>确认删除此行数据？</p>',
                      onOk: () => {
                        this.dataItem.splice(params.index, 1);
                      },
                      onCancel: () => {

                      }
                    });
                  }
                }
              }, '删除')
            ]);

          }
        }

      ],
      columnsView: [
        {title: '序号', width: 80, fixed: 'left', align: 'center', key: 'index',render:(h,params)=>{return h('span', params.index+1);

          }},
        { key:'evaluateItem', title: '评价项目' ,  align: 'center',minWidth: 120 },
        { key:'evaluationContent',title: '评价内容',  align: 'center',minWidth: 170 ,tooltip: true},
        { key:'whether',title: '是/否',  align: 'center',minWidth: 80,render:(h,params)=>{
          if (!params.row.whether) return ""
          return h('span', params.row.whether == '1'?'是':'否')
          }},
      ],
      upUrl: Api.uploadDangerList,
      ruleCustom: {
        companyId: [{required: true, message: '请填写所属单位', trigger: 'change',}],
        createUserName: [{required: true, message: '请填写填报人', trigger: 'change',}],
        phone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(value))) {
              callback(' ');
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],

      },
      tableHeight: 10,
      crectification: [],
      // api
      standardSelectModal: false,
      queryUrl: Api.queryHealthSafety,
      deleteUrl: Api.deleteHealthSafety,
      updateUrl: Api.updateHealthSafety,
      saveUrl: Api.saveHealthSafety,
      downloadUrl: Api.downloadHealthSafety,
      buttonLoading: false,
      dangerModel: false,
    }
  },
  mounted() {
    let _this = this;
    this.dataToQuery = {};
    this.setTableHeight();
    this.query();
  },
  methods: {

    ...pageCommonFunction,
    beforeViewDialogOpen(data){
      this.dataItem = data.row.problemFeedbackList
    },
    templateModCancel(){
      this.templateMod = false;
    },
    saveItem(){
      let list = this.$refs.safetyTemplate.saveAll();
      this.templateMod = false;

      list.forEach(item=>{
        let data = {
          templateId:item.id,
          evaluateItem:item.evaluateItem,
          evaluationContent:item.evaluationContent,
        }
        this.dataItem.push(data);
      })

    },
    beforeEditDialogOpen(data) {
      data.row.healthCompany.createDate = formatDate(new Date(data.row.healthCompany.createDate), "yyyy-MM-dd"),
      this.dataItem = data.row.problemFeedbackList
    },
    cascaderDomIdChangeHandle(data, idField) {
      if (data && data instanceof Array && data.length > 0 && idField) {
        this.$set(this.dataToView.healthCompany, idField, data[data.length - 1])
      }
    },
    cascaderDomNameChangeHandle(data, idField) {
      if (data && idField) {
        this.$set(this.dataToView.healthCompany, idField, data)
      }
    },

    openDangerModal() {
      this.dangerModel = true;
    },
    getColumKey(h,params){
      let key = params.column.key;
      if (!params.row.healthCompany[key]) return "";
      return h('span',params.row.healthCompany[key]);
    },
    renderCellDateAsHealth(h, params) {
      let key = params.column.key;
      if (!params.row.healthCompany[key]) return "";
      return h('span', formatDate(new Date(params.row.healthCompany[key]), "yyyy-MM-dd"))
    },
    selectDanger(row) {
      this.dangerModel = false;
      this.dataToView.dangerId = row.id;
      this.dataToView.dangerName = row.dangerName;
    },
    dictListToMap(arr, key = 'codingCodeId') {
      var map = {}
      arr.map(item => {
        map[item[key]] = item
      })
      return map
    },
    areaCodeToSortName(codeStr) {
      if (!codeStr || codeStr === "") return "";
      var arr = codeStr.split(',')
      var outArr = []
      arr.forEach(codingCodeId => {
        if (this.areaMap[codingCodeId]) {
          outArr.push(this.areaMap[codingCodeId].codingName)
        }
      })
      return outArr.join("·")
    },
    download(params) {
      this.buttonLoading = true
      this.$http.get(Api.downloadHealthSafety + params.row.healthCompany.id, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "职业安全管理现状普查表(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
        this.buttonLoading = false
      })
    },
    importDanger() {
      this.importModal = true;
    },

    uploadExcel(response, file, fileList) {
      //上传完成后执行代码
      if (response.status === 200) {
        this.$Message.success('导入成功');
        this.query()
      } else if (response.status === 201) {
        this.$Message.error("导入失败");
        this.query()
      }
    },
    deleteData(params) {
      this.$Modal.confirm({
        title: '提示',
        content: '<p>确认删除此行数据？</p>',
        onOk: () => {
          let url = this.deleteUrl;
          this.$http.delete(url + '/' + params.row.healthCompany.id, {params: {}}).then((res) => {
            if (res.data.status === 200) {
              this.$Message.success('删除成功');
              this.query()
            } else if (res.data.status === 201) {
              this.$Message.error(res.data.msg);
            }
          }).catch(e => {
            this.$Message.error('删除失败' + e);
          })
        },
        onCancel: () => {
        }
      });
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 44;

      } else {
        this.tableHeight = this.tableHeight - 44;
      }

    },
    setOrgId(data) {
      this.dataToQuery.companyId = data[data.length - 1];
    },
    setOrgName(data) {

    },
    query() {

      this.queryAjax()
    },

    submit(name) {
      this.$set(this.dataToView,'list',this.dataItem)
      this.submitAjax(name);
    },
    addItemInfo() {

      this.templateMod = true;
    },
    createEmptyDataToAdd() {
      this.dataItem = [];
      let healthCompany = {
        companyId: sessionStorage('userId').getObject('userId').companyId,
        companyName: sessionStorage('userId').getObject('userId').companyName,
        twoLevelOrgId: this.user.twoLevelOrgId,
        twoLevelOrgName: this.user.twoLevelOrgName,
        createUserName: this.user.userName,
        userPhone: this.user.mobileNumber,
        createDate:formatDate(new Date(), "yyyy-MM-dd"),
        phone:this.user.mobileNumber,
      }
      return {
        healthCompany:healthCompany,
      }
    },

    downloadFile() {
      this.buttonLoading = true
      this.$http.get(Api.downloadMeasuresList, {
        params: this.dataToQuery,
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "措施清单(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
        this.buttonLoading = false
      })
    },
  },
  watch: {},

}
</script>

<style lang='css' scoped>
@import '../../../../index.css';

.importDanger {
  display: inline-block
}
</style>
